package com.llgz.hotelmanageapi.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.llgz.hotelmanageapi.pojo.DO.UserInfo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Bernie_fang
 * @Description:
 * @create 2021/7/23 10:13
 **/
public class JWTUtil {

    /**
     * 设置过期时间，过期时间为 1 天
     */
    // private static final long EXPIPE_TIME =  24 * 60 * 60 * 1000;
    private static final long EXPIPE_TIME = 24 * 60 * 60 * 1000;

    /**
     * token的密钥
     */
    private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618";

    /**
     * 校验token是否正确
     */
    public static boolean verify(String token) throws JWTVerificationException, IllegalArgumentException, UnsupportedEncodingException {
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        return true;
    }

    /**
     * 获取token中的信息无需密钥也能获得，这里获取登录者的学号
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("id").asString();
        } catch (Exception e) {
            return null;
        }
    }

    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 生成签名
     */
    public static String sign(UserInfo user) {
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIPE_TIME);
            //密钥及算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //附带userId信息，生成签名
            return JWT.create()
                    .withHeader(header)
                    .withClaim("id", user.getId())
                    .withClaim("username", user.getUsername())
                    .withExpiresAt(date)  //设置过期时间
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

}
